﻿using Prism.Commands;
using Prism.Dialogs;
using Prism.Mvvm;
using Rafy.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;

namespace Rafy.Book.ViewModels
{
    public class FmKeMuViewModel : BindableBase, IDialogAware
    {
        public string Title => "添加目录";
        private string _catalogName;
        public string CatalogName
        {
            get => _catalogName;
            set => SetProperty(ref _catalogName, value);
        }

        private int _navType = 10; // 默认选中
        public int NavType
        {
            get => _navType;
            set => SetProperty(ref _navType, value);
        }

        public DelegateCommand SaveCommand { get; }

        public int? cataId { get; set; }   
        public int bookId { get; set; }
        public FmKeMuViewModel()
        {
            SaveCommand = new DelegateCommand(OnSave);
        }

        private void LoadData()
        {
            if(cataId != null && cataId > 0)
            {
                var repo = RF.ResolveInstance<Base_CatalogBookRepository>();
                var catalog = repo.GetById(cataId);
                CatalogName = catalog.F_Name;
                NavType = catalog.F_Cls;
            }
        }
        private void OnSave()
        {
            if (bookId < 1)
            {
                HandyControl.Controls.Growl.Warning("请选择课目", "InfoMessage");
                return;
            }
            // 示例保存逻辑（你可以替换成 Rafy 实体保存）
            var catalog = new Base_CatalogBook();
            if (cataId != null && cataId > 0) 
            {
                catalog.Id = Convert.ToInt32(cataId);
                catalog.PersistenceStatus = PersistenceStatus.Modified;
            }
            Console.WriteLine("Cls="+NavType);
            catalog.F_Name = CatalogName;
            catalog.F_Cls = NavType;
            catalog.F_BooksId = bookId;
           

            var repo = RF.ResolveInstance<Base_CatalogBookRepository>();
            repo.Save(catalog);

            RequestClose.Invoke(new DialogResult(ButtonResult.OK));
        }

        public DialogCloseListener RequestClose { get; }

        //这个方法是允许关闭窗口
        public bool CanCloseDialog()
        {
            return true;
        }
        //关闭方法
        public void OnDialogClosed()
        {
            //RequestClose.Invoke(ButtonResult.Cancel);
            //MessageBox.Show("关闭窗口");
        }
        //打开之前传递过来的参数
        public void OnDialogOpened(IDialogParameters parameters)
        {
            //从上页面中传过来的参数
            cataId = parameters.GetValue<int?>("cataId");
            bookId = parameters.GetValue<int>("bookId");
            Console.WriteLine($"cataId={cataId} bookid={bookId}");
            LoadData();
        }

        
    }
}
